/**
 * 
 */
package cn.gov.msa.collection;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import cn.gov.msa.util.PropertiesTools;
import cn.gov.msa.util.WebServiceTools;
import cn.msa.gov.model.Org;
import cn.msa.gov.model.Role;
import cn.msa.gov.model.UserDetail;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author Administrator
 *
 */
public class LdapService {
	private static Logger  logger = Logger.getLogger(LdapService.class);
	private static String url = PropertiesTools.readProperties("ldap.url");
	
	public static String queryUser(JSONObject param) throws Exception {
		
		if(param.has("username") && !"".equals(param.getString("username")))
			param.put("userName", param.getString("username"));
		if(param.has("orgcode") && !"".equals(param.getString("orgcode")))
			param.put("orgnazations", param.getString("orgcode"));
		
		
        String[] parameter = new String[]{param.toString()};      
    	JSONObject jsonResult = JSONObject.fromObject(WebServiceTools.getDatasByUrl(url, "UserQueryServices_userQueryByCondition", parameter));
    	JSONObject result = new JSONObject();
    	if(jsonResult.getInt("result") == 1){
    		int total = jsonResult.getJSONObject("datas").getJSONObject("table").getJSONObject("row").getInt("total");
    		
    		JSONArray rowsTemp = jsonResult.getJSONObject("datas").getJSONObject("table").getJSONObject("row").getJSONObject("table").getJSONArray("row");
    		JSONArray rows = new JSONArray();
    		for (Object object : rowsTemp) {
				JSONObject row = JSONObject.fromObject(object);
				
				JSONObject rownew = new JSONObject();
				rownew.put("userid", row.getString("userId"));
				rownew.put("username", row.getString("userName"));
				if(row.has("maritimeOrgCode"))
					rownew.put("orgcode", row.getString("maritimeOrgCode"));
				if(row.has("orgName"))
					rownew.put("orgname", row.getString("orgName"));
				if(row.has("deptCode"))
					rownew.put("deptcode", row.getString("deptCode"));
				if(row.has("deptName"))
					rownew.put("deptname", row.getString("deptName"));

				
				rows.add(rownew);
			}
    		
    		result.put("total", total);
    		result.put("rows", rows);
    	}else {
    		result.put("total", "0");
    		result.put("rows", new JSONArray());
    	}
    	
		return result.toString();
	}
	
	public static void main(String[] args) throws Exception {
//		String result = LdapService.queryUser(JSONObject.fromObject("{'orgcode':'0601'}"));
		
//		System.out.println(result);
		
		
//		
//		JSONObject jsonParam = new JSONObject();
//		jsonParam.put("orgName", "盐城东台海事处");
//		
//
//        String[] parameter = new String[]{jsonParam.toString()};   
//        
//    	JSONObject jsonResult = JSONObject.fromObject(WebServiceTools.getDatasByUrl(url, "OrgQueryServices_queryOrgByCondition", parameter));
//
//    	System.out.println(jsonResult);
		
	}
	
 
	

	 

	public static UserDetail getUserDetail(String userid,int isrole) throws Exception{
		
		UserDetail userDetail = new UserDetail();
		
		JSONObject param = new JSONObject();
		
		param.put("userId", userid);
		param.put("isQueryOrgs", "1");
		if(1==isrole) {
			param.put("isQueryRoles", "1");
		}
		
        String[] parameter = new String[]{param.toString()};      
    	JSONObject jsonResult = JSONObject.fromObject(WebServiceTools.getDatasByUrl(url, "UserQueryServices_userQuery4Detail", parameter));
    	logger.info("csp URL："+url+",用户Id:"+jsonResult);
    	if(jsonResult.getInt("result") == 1 && jsonResult.getJSONObject("datas").getJSONObject("table").has("row")){
    		JSONObject jsonUser = jsonResult.getJSONObject("datas").getJSONObject("table").getJSONObject("row");
    		String userName = "".equals(jsonUser.optString("userName")) == false ? jsonUser.optString("userName") : jsonUser.optString("displayName");
    		userDetail.setUserId(jsonUser.getString("uid"));
    		userDetail.setUserName(userName);
    		userDetail.setProposerId(jsonUser.getString("uid"));
    		userDetail.setProposer(userName);
    		if(jsonUser.has("telephoneNumber"))
    			userDetail.setTelePhone(jsonUser.getString("telephoneNumber"));
    		if(jsonUser.has("linkAddress"))
    			userDetail.setContactAddr(jsonUser.getString("linkAddress"));
    		userDetail.setEmail(jsonUser.optString("email"));
    		userDetail.setMobilePhone(jsonUser.optString("mobile"));
    		if(jsonUser.has("orgCode")) {
    			userDetail.setCompanyId(jsonUser.getString("orgCode"));
    		}
    		if(jsonUser.has("table")) {
	    		JSONArray tables = jsonUser.getJSONArray("table");
				for (int i = 0; i < tables.size(); i++) {
					JSONObject table = tables.getJSONObject(i);
					if("org".equals(table.getString("tableName"))) {
						JSONArray orgResult = table.getJSONArray("row");
						for (int j = 0; j <orgResult.size(); j++) {
							JSONObject org = orgResult.getJSONObject(j);
							if(org.has("orgName")) {
								userDetail.setCompany(org.getString("orgName"));
							}else {
								userDetail.setCompany(jsonUser.getString("orgCode"));
							}
						}
					}else if("role".equals(table.getString("tableName"))) {
						JSONArray rows = table.getJSONArray("row");
						List<Role> roles = new ArrayList<Role>();
						for (int j = 0; j < rows.size(); j++) {
							JSONObject row = rows.getJSONObject(j);
							Role role = new Role();
							role.setRolecode(row.optString("roleCode"));
							role.setRolename(row.optString("roleName"));
							roles.add(role);
						}
						userDetail.setRoles(roles);
					}
				}
    		}
    	}
		return userDetail;
	}
	
	public static Org getOrgDetail(String orgCode) throws Exception{
		Org org = new Org();
		
		JSONObject param = new JSONObject();
		
		param.put("orgCode", orgCode);
		
        String[] parameter = new String[]{param.toString()};      
		
        // {"result": "1","info": "组织机构查询成功","datas": {"table": {"tableName": "org","row": {"email": "11@qq.com","maritimeOrgCode": "999999999","orgCode": "999999999","orgId": "999999999","orgStatus": "Active"}}}}
    	JSONObject jsonResult = JSONObject.fromObject(WebServiceTools.getDatasByUrl(url, "OrgQueryServices_queryOrg4Detail", parameter));
    	
    	if(jsonResult.getInt("result") == 1 && jsonResult.getJSONObject("datas").getJSONObject("table").has("row")){
    		JSONObject jsonOrg = jsonResult.getJSONObject("datas").getJSONObject("table").getJSONObject("row");
    		org = (Org) JSONObject.toBean(jsonOrg, Org.class);
    		org.setOrgCode(jsonOrg.getString("orgCode"));
    		org.setMaritimeAgencyCode(jsonOrg.optString("maritimeOrgCode"));
    		org.setMaritimeAgencyName(jsonOrg.optString("maritimeAgency"));
    	}
    	
    	return org;
	}
	

	public static String right(String orgcode) throws Exception{
		JSONObject jsonResult = new JSONObject();
		
		try{
			JSONArray roleArray = new JSONArray();
			roleArray.add("CSP_015_R00001");
	
			JSONObject param = new JSONObject();
			param.put("userId", orgcode);
			param.put("verification", "4ACSP666");
			param.put("roleArray", roleArray);
			
	        String[] parameter = new String[]{param.toString()};      
			
	    	jsonResult = JSONObject.fromObject(WebServiceTools.getDatasByUrl("http://10.32.14.39:8011/csp4a/proxy/UserRoleService_proxy?wsdl", "addUserRole", parameter));
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		return jsonResult.toString();
		
	}
}
